package org.hako.recite.word.tool;

import java.io.File;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

import jxl.Workbook;
import jxl.write.Label;
import jxl.write.WritableSheet;
import jxl.write.WritableWorkbook;

import org.hako.recite.word.parser.WordList;
import org.hako.recite.word.parser.WordListParseException;
import org.hako.recite.word.parser.WordListParser;
import org.hako.recite.word.parser.factory.WordListParserFactory;
import org.hako.recite.word.parser.impl.UnsupportedFileExtensionException;

public class NewAnalyzeKannjiYomi {

	/**
	 * @param args
	 */
	public static void main(String[] args) throws Exception {
		String filePath = "/home/xnnyygn/Programs/recite-word/jp34.xls";
		WordList wordList = parseWordListFile(filePath);
		NewKannjiYomiAnalyzer analyzer = new NewKannjiYomiAnalyzer();
		KannjiYomiAnalysisResult result = analyzer.analyze(wordList.getWords());
		WritableWorkbook workbook = Workbook.createWorkbook(new File(
				"/tmp/output.xls"));
		WritableSheet sheet = workbook.createSheet("First", 0);
		int row = 0;
		for (Map.Entry<KannjiYomiPair, List<String>> entry : result
				.getKannjiWordMap().entrySet()) {
			KannjiYomiPair pair = entry.getKey();
			Label label = new Label(0, row, pair.getKannji());
			sheet.addCell(label);
			label = new Label(1, row, pair.getYomi());
			sheet.addCell(label);
			label = new Label(2, row, pair.isYonn() ? "0" : "1");
			sheet.addCell(label);
			String items = Arrays.toString(entry.getValue().toArray());
			label = new Label(3, row, items.substring(1, items.length() - 1));
			sheet.addCell(label);
			row++;
			// System.out.println(pair.getKannji() + "\t" + pair.getYomi() +
			// "\t"
			// + (pair.isYonn() ? '0' : '1') + "\t"
			// + Arrays.toString(entry.getValue().toArray()));
		}
		workbook.write();
		workbook.close();
		// String HR = "====================================================";
		// System.out.println(HR);
		// for (Word word : result.getAnalysisFailureWords()) {
		// System.out.println(word.get(0) + "\t" + word.get(1));
		// }
		// System.out.println(HR);
		// System.out.println(result.getAnalysisFailureWords().size());
	}

	/**
	 * Parse word list from file.
	 * 
	 * @param filePath
	 * @return
	 * @throws UnsupportedFileExtensionException
	 * @throws WordListParseException
	 */
	private static WordList parseWordListFile(String filePath)
			throws UnsupportedFileExtensionException, WordListParseException {
		WordListParserFactory parserFactory = new WordListParserFactory();
		WordListParser parser = parserFactory.getParser(filePath);
		WordList wordList = parser.parse(filePath);
		return wordList;
	}
}
